import React, { useState, useEffect } from 'react';
import { history, connect, Dispatch } from 'umi';
import { StateType } from '@/models/login';
import { LoginParamsType } from '@/services/login';
import { ConnectState } from '@/models/connect';
import LoginForm from './components/Login';
import { reloadAuthorized } from '@/utils/Authorized';
import { getPageQuery } from '@/utils/utils';
import styles from './style.less';
import { loginWechatgetInfo } from '@/services/login'
import { WechatOutlined } from "@ant-design/icons";
import { message, Checkbox } from 'antd';
import { checkSystem, logOut,checkHost,tip,hasSignUp } from '@/utils/utils'
const { Tab, UserName, Password, Submit } = LoginForm;
interface LoginProps {
  dispatch: Dispatch;
  userLogin: StateType;
  submitting?: boolean;
}



const Login: React.FC<LoginProps> = (props) => {
  const { submitting } = props;
  const [type, setType] = useState<string>('account');
  const remember_me_status = localStorage.getItem('remember_me') === 'true' ? true : false
  const [remember_me, setRemember] = useState<boolean>(remember_me_status);

  const handleSubmit = (values: LoginParamsType) => {
    const { dispatch } = props;
    dispatch({
      type: 'login/login',
      payload: { ...values, type },
    });
  };
  const loginWechat = () => {
    location.href = `/index/index/login_weixin`
  }
  const changeRememberMe = (e) => {
    localStorage.setItem('remember_me', e.target.checked)
    setRemember(e.target.checked)
  }
  useEffect(() => {
    const remember_me = localStorage.getItem('remember_me')
    const uid = localStorage.getItem('id')
    if (remember_me === 'true' && uid) {
      return history.push('/dashboard')
    }
    const id = props.location.query.id;
    const is_sw = props.location.query.is_sw;
    const jsSyj = props.location.query.isSjy;
    if (!checkSystem()&&!jsSyj) {
      if (id) {
        window.location.href = `/mobile/index.html#/login?id=${id}&is_sw=${is_sw}`
      } else {
        window.location.href = `/mobile/index.html#/login`
      }
      return
    }
    if (id === 'no') return message.error('绑定失败，请重新绑定');
    if (isNaN(id * 1)) return;
    if (remember_me === 'false') {
      logOut()
    }
    loginWechatgetInfo({ id ,is_sw}).then(response => {
      if (!response) return message.error('登陆失败');
      if (response.status === 2) return message.error('账户或密码错误');
      message.success('登录成功');
      if (response.type === 2) {
        localStorage.setItem('antd-pro-authority', `["${response.type}"]`);
      } else {
        const power = response.types && response.types.power;
        localStorage.setItem('antd-pro-authority', `[${power}]`);
      }
      localStorage.setItem('name', response.name);
      localStorage.setItem('id_number', response.id_number);
      localStorage.setItem('type', response.type);
      localStorage.setItem('subjects', response.subjects);
      localStorage.setItem('id', response.id);
      localStorage.setItem('userinfo', JSON.stringify(response));
      const date = new Date();
      localStorage.setItem('logintime', date.getTime() + '');
      reloadAuthorized();
      const urlParams = new URL(window.location.href);
      const params = getPageQuery();
      let { redirect } = params as { redirect: string };
      if (redirect) {
        const redirectUrlParams = new URL(redirect);
        if (redirectUrlParams.origin === urlParams.origin) {
          redirect = redirect.substr(urlParams.origin.length);
          if (redirect.match(/^\/.*#/)) {
            // redirect = redirect.substr(redirect.indexOf('#') + 1);
            redirect = '/dashboard';
          }
        } else {
          redirect = '/dashboard';
        }
      }
      history.replace(redirect || '/');
    })
  }, [])
  return (
    <div className={styles.main}>
      <LoginForm activeKey={type} onTabChange={setType} onSubmit={handleSubmit}>
        <Tab key="account" tab="登录">
        </Tab>
        {/* <Tab key="idnumber" tab="身份证号登录">
        </Tab> */}
        <UserName
          name="userName"
          placeholder="账号：请输入您的身份证号"
          rules={[
            {
              required: true,
              message: '请输入账号',
            },
          ]}
        />
        <Password
          name="password"
          placeholder="密码(身份证号后四位)"
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
          ]}
        />
        <div className={styles['user-handle']}>
          <h4 className={styles.wechat} onClick={loginWechat}>
            {
             checkHost() && <React.Fragment><WechatOutlined
                style={{ color: "#62b900", marginRight: 5 }} />微信登录</React.Fragment>
            }
            {
              window.location.host==='xuexi.shejiyuan.com'&&<React.Fragment><WechatOutlined
              style={{ color: "#62b900", marginRight: 5 }} />微信登录</React.Fragment>
            }
          </h4>
          <Checkbox style={{ float: 'right' }} checked={remember_me} onChange={changeRememberMe}>记住我</Checkbox>
        </div>
        <Submit loading={submitting}>登录</Submit>
      </LoginForm>
      <hr />
      {
        hasSignUp()?<p style={{ marginTop: 20 }}>还没有账号？<a href={`https://${tip()}/pc`}>立即报名</a></p>:null
      }
      
    </div>
  );
};

export default connect(({ login, loading }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))(Login);
